(function ($) {
	function showMailItem(hash) {
		// TODO: parse hash
		$('table#inbox-mail-overview, div#inbox-mail-item').toggle();
	}

	function showMailOverview() {
		$('table#inbox-mail-overview, div#inbox-mail-item').toggle();
	}

	function initializeMail() {
		var $tr = $('table#inbox-mail-overview tbody > tr:first'), item = mail['mid-1231'];
		$.each(mail, function(mid) {
			var $row = $tr.clone(), item = mail[mid];
			$row.attr('data-item', '#inbox/'+ mid)
			$row.show().find('td:nth-child(2)').html(item.from);
			$row.find('td:nth-child(3)').html(item.subject + '<small class="pull-right">'+ item.date +'</small>');
			$row.appendTo('table#inbox-mail-overview tbody');
		});
	}

	$(document).ready(function() {
		if(window.location.hash) {
			var hash = window.location.hash;
			showMailItem(hash);
		} else {
			initializeMail();
		}

		$('table#inbox-mail-overview tr').bind('click', function() {
			if(history.pushState) {
				history.pushState(null, null, '#inbox/123');
				showMailItem('#inbox/123');
			}
			else {
				// location.hash = '#inbox/123';
			}
		});

		// mark correct nav item
		var navClass = 'inbox';
		if (window.location.search.length > 0) navClass = window.location.search.substring(1);
		$('div#inbox-navigation ul li.'+ navClass).addClass('active');
	});

	// Used to detect initial (useless) popstate.
	// If history.state exists, assume browser isn't going to fire initial popstate.
	var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
	console.log('popped', popped);

	$(window).bind('popstate', function (event) {
		// Ignore inital popstate that some browsers fire on page load
		var initialPop = !popped && location.href == initialURL
		popped = true
		if (initialPop) return;

		console.log('popped', popped);
		showMailOverview();
	});
})(jQuery);